<template>
  <div>
    <div class="input-section">
      <div class="right">
        <el-input
          v-model="searchQuery"
          placeholder="请输入申请用户ID"
          style="
            width: 500px;
            height: 40px;
            margin-bottom: 20px;
            margin-top: 20px;
          "
          :prefix-icon="Search"
          clearable
        />
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
      <div class="button-group">
        <el-button @click="exportToExcel" type="success">导出 Excel</el-button>

        <el-button
          type="danger"
          @click="handleBatchDelete"
          :disabled="selectedRows.length === 0"
          >批量删除</el-button
        >
      </div>
    </div>
    <el-table
      ref="tableRef"
      :data="tableData"
      style="width: 100%; height: 520px"
      row-key="id"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="40" />
      <el-table-column prop="id" label="申请ID" width="100" sortable />
      <el-table-column prop="userId" label="申请用户ID" width="100" sortable />
      <el-table-column
        prop="type"
        label="申请类型"
        width="120"
        :filters="typeFilters"
        :filter-method="filterType"
        filter-placement="bottom-end"
      >
        <template #default="{ row }">
          <el-tag v-if="row.type === 0" type="success">账号注册</el-tag>
          <el-tag v-else-if="row.type === 1" type="info">加入社团</el-tag>
          <el-tag v-else-if="row.type === 2" type="danger">退出社团</el-tag>
          <el-tag v-else-if="row.type === 3" type="success">参与活动</el-tag>
          <el-tag v-else-if="row.type === 4" type="danger">退出活动</el-tag>
          <el-tag v-else type="warning">未知类型</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="result"
        label="审核结果"
        width="100"
        :filters="resultFilters"
        :filter-method="filterResult"
        filter-placement="bottom-end"
      >
        <template #default="{ row }">
          <el-tag v-if="row.result === 0" type="warning">待审核</el-tag>
          <el-tag v-else-if="row.result === 1" type="success">通过</el-tag>
          <el-tag v-else-if="row.result === 2" type="danger">拒绝</el-tag>
          <el-tag v-else type="info">未知结果</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="additionalInfo" label="附加信息" width="80" />
      <el-table-column prop="reason" label="申请原因" width="210" />
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="100"
        sortable
      />
      <el-table-column
        prop="updateTime"
        label="更新时间"
        width="100"
        sortable
      />
      <el-table-column
        prop="isDelete"
        label="是否删除"
        width="100"
        :filters="deleteFilters"
        :filter-method="filterResult"
        filter-placement="bottom-end"
      >
        <template #default="{ row }">
          <el-tag v-if="row.isDelete === 0" type="success">正常</el-tag>
          <el-tag v-else-if="row.isDelete === 1" type="warning">已删除</el-tag>
          <el-tag v-else type="danger">未知类型</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="{ row }">
          <el-button
            size="small"
            @click="handleApplicationReview(row, true)"
            type="success"
            :disabled="row.result !== 0"
          >
            同意
          </el-button>
          <el-button
            size="small"
            @click="handleApplicationReview(row, false)"
            type="danger"
            :disabled="row.result !== 0"
          >
            拒绝
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-section">
      <span class="record-count"> 共查询到 {{ total }} 条记录 </span>
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        v-model:page-size="pageSize"
        v-model:current-page="currentPage"
        :page-sizes="[4, 10, 20, 50]"
        @current-change="loadTableData"
        @size-change="loadTableData"
      />
    </div>
    <el-dialog title="新增用户申请" v-model="dialogVisible" width="600px">
      <el-form :model="form" label-width="120px">
        <el-form-item label="用户ID">
          <el-input v-model="form.userId" placeholder="请输入用户ID" />
        </el-form-item>
        <el-form-item label="申请理由">
          <el-input v-model="form.reason" placeholder="请输入申请理由" />
        </el-form-item>
        <el-form-item label="申请类型">
          <el-select v-model="form.type" placeholder="请选择申请类型">
            <el-option label="账号注销" value="0" />
            <el-option label="加入社团" value="1" />
            <el-option label="退出社团" value="2" />
            <el-option label="参与活动" value="3" />
            <el-option label="退出活动" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="附加信息">
          <el-input
            v-model="form.additionalInfo"
            placeholder="请输入附加信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, watch } from "vue";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus"; // 添加这行
import { Search } from "@element-plus/icons-vue";
import { getUserApplicationListAPI } from "@/apis/user";
import { addUserApplicationAPI } from "@/apis/user";

import { deleteUserApplicationAPI } from "@/apis/user";
import { doReviewAPI } from "@/apis/review";
import { useUserStore } from "@/stores/user";
import * as XLSX from "xlsx";

// 导出为 Excel
const exportToExcel = () => {
  if (!tableData.value.length) {
    ElMessage.warning("没有可导出的数据");
    return;
  }
  console.log("表格数据：", tableData.value);
  // 提取你想要导出的字段
  const exportData = tableData.value.map((item) => ({
    用户ID: item.userId,
    申请原因: item.reason,
  }));

  const worksheet = XLSX.utils.json_to_sheet(exportData);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, "社团信息");

  // 下载 Excel 文件
  XLSX.writeFile(
    workbook,
    `社团列表_${new Date().toISOString().slice(0, 10)}.xlsx`
  );
};
const userStore = useUserStore();

// 搜索和分页
const searchQuery = ref("");
const tableData = ref([]); // 表格数据
const total = ref(); // 总记录数
const currentPage = ref(1); // 当前页码
const pageSize = ref(4); // 每页记录数

// 筛选器
const typeFilters = [
  { text: "账号注册", value: 0 },
  { text: "加入社团", value: 1 },
  { text: "退出社团", value: 2 },
  { text: "参与活动", value: 3 },
  { text: "退出活动", value: 4 },
];

const resultFilters = [
  { text: "待审核", value: 0 },
  { text: "通过", value: 1 },
  { text: "拒绝", value: 2 },
];

const deleteFilters = [
  { text: "正常", value: 0 },
  { text: "已删除", value: 1 },
];
// 加载表格数据的方法
const loadTableData = async () => {
  try {
    const response: any = await getUserApplicationListAPI(
      currentPage.value,
      pageSize.value,
      searchQuery.value ? parseInt(searchQuery.value) : null
    );
    console.log("接口返回数据:", response);

    if (
      response.code === 0 &&
      response.data &&
      Array.isArray(response.data.records)
    ) {
      tableData.value = response.data.records.map((record: any) => ({
        id: record.id,
        userId: record.userId || 0,
        reason: record.reason || "无申请原因",
        createTime: record.createTime || "-",
        updateTime: record.updateTime || "-",
        result: record.result,
        type: record.type,
        additionalInfo: record.additionalInfo || "无附加信息",
        isDelete: record.isDelete || 0,
      }));
      total.value = response.data.total || 0; // 设置总记录数
    } else {
      tableData.value = [];
      total.value = 0;
      ElMessage.warning("未找到用户申请数据");
    }
  } catch (error) {
    console.error("加载用户申请列表失败:", error);
    tableData.value = [];
    total.value = 0;
    ElMessage.error("加载用户申请列表失败，请稍后重试");
  }
};

// 搜索功能
const handleSearch = () => {
  if (searchQuery.value) {
    const searchId = parseInt(searchQuery.value);
    if (!isNaN(searchId)) {
      currentPage.value = 1; // 重置到第一页
      loadTableData();
    } else {
      ElMessage.warning("请输入有效的用户ID");
    }
  } else {
    loadTableData();
  }
};

// 监听搜索框输入
watch(searchQuery, (newVal) => {
  if (!newVal) {
    loadTableData(); 
  }
});
const resetSearch = () => {
  searchQuery.value = "";
  loadTableData(); 
};
// 用户申请审核（同意/拒绝）方法
const handleApplicationReview = async (
  row: any, 
  isAccept: boolean
) => {
  // 1. 安全检查：确保只有未审核的申请可以操作
  if (row.result !== 0) {
    ElMessage.warning("该申请已审核，无法再次操作");
    return;
  }

  const actionText = isAccept ? "同意" : "拒绝";
  const resultValue = isAccept ? 1 : 2;

  try {
    // 2. 弹出对话框，让用户输入原因
    const { value: reason } = await ElMessageBox.prompt(
      `请输入${actionText}原因`,
      `${actionText}申请`,
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputValue: isAccept ? "同意该申请" : "",
        inputValidator: (val: string) => {
          if (!isAccept && (!val || val.trim() === "")) {
            return "拒绝原因不能为空";
          }
          return true;
        },
      }
    );

    // 3. 获取当前审核人的ID
    const reviewerId = userStore.id;
    if (!reviewerId) {
      ElMessage.error("无法获取当前用户信息，请重新登录");
      return;
    }

    // 4. 调用统一的审核接口 doReviewAPI
    const response: any = await doReviewAPI(
      reviewerId,
      row.type,
      row.id,
      reason,
      resultValue
    );

    // 5. 处理后端返回的结果
    if (response && response.code === 0) {
      ElMessage.success(`用户申请已${actionText}`);
      await loadTableData();
    } else {
      ElMessage.error(
        `${actionText}失败：` +
          (response && response.message
            ? response.message
            : "系统错误，请联系管理员")
      );
    }
  } catch (error: any) {
    if (error === "cancel") {
      ElMessage.info(`已取消${actionText}操作`);
    } else {
      ElMessage.error(`${actionText}失败，请查看控制台`);
      console.error("审核操作异常:", error);
    }
  }
};

const selectedRows = ref<any[]>([]); // 存储选中的申请记录
//批量删除
const handleBatchDelete = async () => {
  try {
    // 检查是否有选中记录
    if (selectedRows.value.length === 0) {
      return ElMessage.warning("请至少选择一条申请记录");
    }

    // 构造确认消息（显示部分申请ID）
    const applicationIds = selectedRows.value.map((app) => `#${app.id}`);
    const displayIds =
      applicationIds.length > 3
        ? `${applicationIds.slice(0, 3).join(", ")}等${applicationIds.length}条`
        : applicationIds.join(", ");
    await ElMessageBox.confirm(
      `确定删除选中的 ${selectedRows.value.length} 条用户申请吗？\n（${displayIds}）`,
      "警告",
      {
        confirmButtonText: "确定删除",
        cancelButtonText: "取消",
        type: "warning",
        distinguishCancelAndClose: true,
        confirmButtonClass: "el-button--danger",
        customClass: "message-box-custom",
      }
    );

    // 显示加载状态
    const loading = ElLoading.service({
      lock: true,
      text: `正在删除 ${selectedRows.value.length} 条申请...`,
      background: "rgba(0, 0, 0, 0.7)",
    });
    const ids = selectedRows.value.map((row) => row.id.toString());

    // 调用删除接口
    const response: any = await deleteUserApplicationAPI(ids);
    loading.close();

    // 处理响应
    if (response.code === 0) {
      ElMessage.success({
        message: `成功删除 ${ids.length} 条用户申请`,
        duration: 3000,
      });
      selectedRows.value = []; // 清空选中状态
      await loadTableData(); // 刷新数据
    } else {
      throw new Error(response.message || "批量删除失败");
    }
  } catch (error) {
    // 忽略用户取消操作
    if (error !== "cancel") {
      console.error("批量删除申请失败:", {
        error,
        selectedIds: selectedRows.value.map((r) => r.id),
        timestamp: new Date().toISOString(),
      });
      ElMessage.error({
        message: `批量删除失败: ${error.message || "未知错误"}`,
        duration: 5000,
      });
    }
  }
};

onMounted(() => {
  loadTableData(); // 组件挂载时加载数据
});

const dialogVisible = ref(false); // 控制新增申请对话框显示状态

const form = ref({
  userId: 0,
  reason: "",
  type: 0, // 默认申请类型
  additionalInfo: 0,
});

const handleAdd = () => {
  dialogVisible.value = true; // 打开新增申请对话框
};

const handleSubmit = async () => {
  try {
    const { userId, reason, type, additionalInfo } = form.value;

    // 校验表单数据是否完整
    if (!userId || !reason || !type || !additionalInfo) {
      ElMessage.warning("请填写完整的申请信息");
      return;
    }

    // 调用接口提交数据
    const response: any = await addUserApplicationAPI(
      userId,
      reason,
      type,
      additionalInfo
    );
    console.log("新增用户申请接口返回值:", response);

    if (response.code === 0) {
      ElMessage.success("新增申请成功");
      dialogVisible.value = false; // 关闭对话框
      loadTableData(); // 重新加载表格数据
    } else {
      ElMessage.error("新增申请失败：" + response.message);
    }
  } catch (error: any) {
    console.error("新增申请失败:", error);
    ElMessage.error("新增申请失败，请稍后重试");
  }
};

// 筛选方法
const filterType = (value: any, row: any) => row.type === value;
const filterResult = (value: any, row: any) => row.result === value;
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows;
};
</script>

<style scoped>
.input-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.button-group {
  display: flex;
  gap: 10px;
}

.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.record-count {
  font-size: 14px;
  color: #666;
}
.right {
  display: flex;
  align-items: center;
  gap: 10px;
}
</style>
